const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
// const bodyparser = require('koa-bodyparser')
const bodyparser = require('koa-better-body');
const cors = require('koa2-cors');
const logger = require('koa-logger')

// const index = require('./routes/index')
// const users = require('./routes/users')
// const message = require('./routes/message');
// const friend = require('./routes/friend');
// const group = require('./routes/group');
const routes = require('./routes/index');
// 连接数据库
const mongoose = require('mongoose');
const DB_URL = 'mongodb://localhost:27017/chatroom';
mongoose.connect(DB_URL);
const db = mongoose.connection;
db.on('connected', function () {
	console.log('mongoose connect =======> success')
})

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(cors({
  origin: '*', // 允许来自所有域名请求 "Access-Control-Allow-Origin"
  // credential: true, // 是否允许发送cookie，当设置成允许请求携带cookie时，需要保证"Access-Control-Allow-Origin"是服务器有的域名，而不能是"*""
  allowMethods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
  allowHeaders: ['x-access-token', 'Content-Type'] // "Access-Control-Allow-Headers"
})) // 解决跨域

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
// app.use(index.routes(), index.allowedMethods())
// app.use(users.routes(), users.allowedMethods())
// app.use(message.routes(), message.allowedMethods())
// app.use(friend.routes(), friend.allowedMethods());
// app.use(group.routes(), group.allowedMethods());
routes(app);
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
